﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Dragoon.RoboBattle.HIC
{
  class RobotsRenderer : EffectComponent
  {
    Vector3 _scale = Vector3.One * 0.00625f;
    readonly ISimulator _simulator;
    readonly ICamera _camera;
    Model _robotModel;

    public RobotsRenderer(Game g, ISimulator sim, ICamera cam)
      : base(g,"robots")
    {
      _simulator = sim;
      _camera = cam;
    }

    protected override void LoadContent()
    {
      _robotModel = Game.Content.Load<Model>("robot");
      var scalef = Measurements.RobotLength / (_robotModel.Meshes[0].BoundingSphere.Radius * 2.0f);
      _scale = Vector3.One * scalef;
      foreach (ModelMesh mesh in _robotModel.Meshes)
        foreach (ModelMeshPart meshPart in mesh.MeshParts)
          meshPart.Effect = _effect.Clone(GraphicsDevice);
      base.LoadContent();
    }

    public void DrawRobot(IRobot r)
    {
      Matrix worldMatrix = Matrix.CreateRotationY(r.Rotation + MathHelper.PiOver2) *
        Matrix.CreateScale(_scale)                
        * Matrix.CreateTranslation(r.Position);
      Matrix[] xwingTransforms = new Matrix[_robotModel.Bones.Count];
      _robotModel.CopyAbsoluteBoneTransformsTo(xwingTransforms);
      foreach (ModelMesh mesh in _robotModel.Meshes)
      {
        foreach (Effect currentEffect in mesh.Effects)
        {
          currentEffect.CurrentTechnique = currentEffect.Techniques["Colored"];
          currentEffect.Parameters["xWorld"].SetValue(xwingTransforms[mesh.ParentBone.Index] * worldMatrix);
          currentEffect.Parameters["xView"].SetValue(_camera.ViewMatrix);
          currentEffect.Parameters["xProjection"].SetValue(_camera.ProjectionMatrix);
          currentEffect.Parameters["xLightDirection"].SetValue(_camera.LightDirection);
        }
        mesh.Draw();
      }
    }

    public override void Draw(GameTime gameTime)
    {

     // GraphicsDevice.RenderState.FillMode = FillMode.WireFrame;
      foreach (var r in _simulator.Robots)
        DrawRobot(r);
    }
  }
}
